package org.biz.handler;

import org.biz.common.Result;
import org.biz.exception.BussinessLogicException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class ExceptionHandler extends AbstractErrorController {

    public ExceptionHandler(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    private static String errorPath = "/error";

    @Autowired
    private ResourceUrlProvider resourceUrlProvider;

    @Override
    public String getErrorPath() {
        return errorPath;
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(BussinessLogicException.class)
    @ResponseBody
    public Result restErrorHandler(HttpServletRequest req, BussinessLogicException ex) throws Exception {
        return Result.error(ex.getExceptionEnum().getCode(), ex.getExceptionEnum().getMsg());
    }

    @RequestMapping("/error")
    public ModelAndView errorHandler(HttpServletRequest req, Exception ex) {
        Map<String, Object> model = new HashMap<>();
        model.put("urls", this.resourceUrlProvider);
        model.put("exception", ex);
        return new ModelAndView("error", model);
    }
}